package com.coe3.handle;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import com.coe3.data.Information;
import com.daydr3am.thenation.TheNationMain;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;

public class DecompressAsync extends AsyncTask<String, String, String>  {
	
	private String _zipFile; 
	private String _location;
	private Activity mActivity;
	
	public DecompressAsync(Activity activity, String zipFile, String location) {
		this.mActivity = activity;
		_zipFile = zipFile; 
	    _location = location; 
	    
	    _dirChecker(""); 
	}
	
	@Override
    protected void onPreExecute() {
        super.onPreExecute();
        TheNationMain.getInstanceProgressDialong(mActivity).show();
    }

	@SuppressLint("WorldReadableFiles")
	@Override
    protected String doInBackground( String... aurl ) {
		
		try {
			unzip( _zipFile, _location + File.separator );
			Information.logDEBUG("delete: " + _zipFile + " is " + (new File(_zipFile).delete()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
        return null;
    }
    

	@Override
    protected void onPostExecute(String unused) {
//    	mStore.dismissProgress();
		TheNationMain.dismissProgress(mActivity);
    }
    
    public void unzip() {
		try {
			FileInputStream fin = new FileInputStream(_zipFile); 
			ZipInputStream zin = new ZipInputStream(fin); 
			ZipEntry ze = null;
			while ((ze = zin.getNextEntry()) != null) {
				Log.v("Decompress", "Unzipping " + ze.getName());
				if(ze.isDirectory()) { 
					_dirChecker(ze.getName()); 
				} else {
					FileOutputStream fout = new FileOutputStream(_location + ze.getName()); 
					for (int c = zin.read(); c != -1; c = zin.read()) { 
						fout.write(c); 
					} 
				
					zin.closeEntry(); 
					fout.close();
				}//end if
			}
			zin.close();
		} catch (Exception e) {
			// TODO: handle exception
			Log.e("Decompress", "unzip", e);
		}
	}

    private void _dirChecker(String dir) { 
		File f = new File(_location + dir); 
		
		if(!f.isDirectory()) { 
		  f.mkdirs(); 
		} 
	} 
    
    private final static int BUFFER_SIZE = 32 * 1024;
    /**
	   * Unzip a zip file.  Will overwrite existing files.
	   * 
	   * @param zipFile Full path of the zip file you'd like to unzip.
	   * @param location Full path of the directory you'd like to unzip to (will be created if it doesn't exist).
	   * @throws IOException
	   */
	  public static void unzip(String zipFile, String location) throws IOException {
	      int size;
	      byte[] buffer = new byte[BUFFER_SIZE];

	      try {
	          if ( !location.endsWith("/") ) {
	              location += "/";
	          }
	          File f = new File(location);
	          if(!f.isDirectory()) {
	              f.mkdirs();
	          }
	          ZipInputStream zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile), BUFFER_SIZE));
	          try {
	              ZipEntry ze = null;
	              while ((ze = zin.getNextEntry()) != null) {
	                  String path = location + ze.getName();
	                  File unzipFile = new File(path);

	                  if (ze.isDirectory()) {
	                      if(!unzipFile.isDirectory()) {
	                          unzipFile.mkdirs();
	                      }
	                  } else {
	                      // check for and create parent directories if they don't exist
	                      File parentDir = unzipFile.getParentFile();
	                      if ( null != parentDir ) {
	                          if ( !parentDir.isDirectory() ) {
	                              parentDir.mkdirs();
	                          }
	                      }

	                      // unzip the file
	                      FileOutputStream out = new FileOutputStream(unzipFile, false);
	                      BufferedOutputStream fout = new BufferedOutputStream(out, BUFFER_SIZE);
	                      try {
	                          while ( (size = zin.read(buffer, 0, BUFFER_SIZE)) != -1 ) {
	                              fout.write(buffer, 0, size);
	                          }

	                          zin.closeEntry();
	                      }
	                      finally {
	                          fout.flush();
	                          fout.close();
	                      }
	                  }
	              }
	          }
	          finally {
	              zin.close();
	          }
	      }
	      catch (Exception e) {
	          Log.e("chud", "Unzip exception", e);
	      }
	  }
}
